package yl.hs.bmipfull.service.salemanage.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.salemanage.*;
import yl.hs.bmipfull.pojo.salemanage.BuildProjectInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.CustomerInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.LinkerInfoEntity;
import yl.hs.bmipfull.pojo.system.UserInfoEntity;
import yl.hs.bmipfull.service.salemanage.ICustomerInfoService;
import yl.hs.bmipfull.service.salemanage.ISaleSysTagsService;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.SubmitModel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CustomerInfoServiceImpl
 *
 * @author 谢景广
 * @category
 * @date 2021-05-17
 */
@Service
public class CustomerInfoServiceImpl extends SaleBaseService implements ICustomerInfoService {

    @Autowired
    private SqlSession session;
    @Autowired
    private ISaleSysTagsDao tagsDao;
    @Autowired
    private ISaleContractProductsDao productsDao;
    @Autowired
    private ILinkerInfoDao infoDao;
    @Autowired
    private ISaleContractDao contractDao;
    @Override
    public PageResult<CustomerInfoEntity> queryPage(PageQuery query, int rowNum, int page) {
        PageResult<CustomerInfoEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(), CustomerInfoEntity.class);
        result.setPage(page);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        query.checkSortSides(CustomerInfoEntity.class);
        query.getQuery().put("sortSide", String.join(",", query.getSortSides()));
        result.setRecords(customerDao.queryCountByCondition(query.getQuery(), null, filters));
        var results = customerDao.queryListByCondition(query.getQuery(), null, filters);
        for (CustomerInfoEntity item : results) {
            var contract = contractDao.queryByCustomerSN(item.getSn());
            if(contract.size()>0){
                item.setSaleName(contract.get(0).getSalerName());
            }else{
                item.setSaleName("");
            }
            item.setLinerList(infoDao.findCustomerLinkerList(item.getSn()));
            try {
                var cate = productsDao.queryGroupByContractSn(item.getSn());
                item.setAddressPY(cate.toString());
            }catch (Exception ee){
                item.setAddressPY(null);
            }
        }
        result.setData(results);
        return result;
    }


    @Override
    @Transactional
    public Integer saveCustomer(SubmitModel form) throws Exception {
        var user = HsApp.getCurrent();
        int result = 0;
        if (Tl.isEmpty(form.getSn())) {
            var customer = new CustomerInfoEntity();
            Tl.getChangeLog(customer, form.getData());
            customer.setOrganizationCode(getDepartSN());
            customer.setOrganizationSN(user.getDutySN());
            result = createCustomer(customer);
            form.setSn(customer.getSn());
        } else {
            var customer = customerDao.findBySN(form.getSn());
            var backJson = customer.toJson();
            var changeLog = Tl.getChangeLog(customer, form.getData());
            customer.setPYFieldValue();
            customer.setOrganizationCode(getDepartSN());
            customer.setOrganizationSN(user.getDutySN());
            result = customerDao.update(customer);
            saveGS(
                    customer.getSn(),
                    customer.getCustName(),
                    String.join(",",
                            customer.getCustName(),
                            customer.getAddress(),
                            customer.getArea()
                    ),
                    customer,
                    HsApp.getCurrent().getUserSN(),
                    null
            );
            writeLog(ActionType.UPDATE, customer.getSn(), changeLog, backJson, UserInfoEntity.class);
        }
        return result;
    }

    @Override
    @Transactional
    public Integer createCustomer(CustomerInfoEntity entity) throws Exception {
        var newSn = queryNewSN(CustomerInfoEntity.class);
        entity.setSn(newSn);
        entity.setPYFieldValue();
        var result = customerDao.insertNew(entity);

        var shareCode = writeUserTag(entity.getSn(), entity.getClass(), RelationType.CREATE.toString());
        saveGS(
                entity.getSn(),
                entity.getCustName(),
                String.join(",",
                        entity.getCustName(),
                        entity.getAddress(),
                        entity.getArea()
                ),
                entity,
                HsApp.getCurrent().getUserSN(),
                shareCode
        );
        writeLog(ActionType.CREATE, newSn, "", "", UserInfoEntity.class);
        return result;
    }


    @Override
    @Transactional
    public Integer deleteBySn(String[] snArray) {
        for (String s : snArray) {
            var entitylist = contractdao.queryList(new HashMap<>() {
                {
                    put("customerSN", s);
                }
            });
            if (entitylist.size() > 0) {
                return -2;
            }
        }
        var result = customerDao.deleteCustomers(snArray);
        if (result > 0) {
            deleteGs(snArray);
        }
        return result;
    }

    @Override
    public CustomerInfoEntity findBySN(String sn) {
        return customerDao.findBySN(sn);
    }

    @Override
    public List<CustomerInfoEntity> getList(Short state) {
        return customerDao.queryList(state, getTagSNs());
    }

    @Override
    public CustomerInfoEntity findByName(String customerName, String sn) {
        return customerDao.findByName(customerName, sn);
    }

    @Override
    public Boolean customerValida(String customerName, String sn) {
        CustomerInfoEntity customerInfoEntity = customerDao.findByName(customerName, sn);
        if (customerInfoEntity == null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional
    public String saveCustomer(String customerName) throws Exception {
        CustomerInfoEntity customerInfoEntity = new CustomerInfoEntity();
        customerInfoEntity.setCustName(customerName);
        createCustomer(customerInfoEntity);
        return customerInfoEntity.getSn();
    }

    @Override
    public boolean recovery(List<String> snArray) {
        return customerDao.recovery(snArray) > 0;
    }

    @Override
    public Integer changeStateBySn(String[] snArray, short state) {
        int result = customerDao.changeStateBySn(snArray, state);
        if (result > 0) {
            forWriteLog(snArray, state);
        }
        return result;
    }

    @Override
    public Integer customerTransfer(String mainSN, String userSN) {
        int result = 0;
        //修改客户用户所有权
        var customerTagList = tagsDao.queryByMainSN(mainSN, Tl.getDBMapCode(UserInfoEntity.class));
        for (var customerTag : customerTagList) {
            customerTag.setTagSN(userSN);
            result = tagsDao.update(customerTag);
        }
        //修改联系人用户所有权
        var linkList = linkerInfoDao.findCustomerLinkerList(mainSN);
        for (var linker : linkList) {
            var linkTagList = tagsDao.queryByMainSN(linker.getSn(), Tl.getDBMapCode(UserInfoEntity.class));
            for (var linkerTag : linkTagList) {
                linkerTag.setTagSN(userSN);
                tagsDao.update(linkerTag);
            }
        }
        //修改工地信息所有权用户
        var projectList = projectInfoDao.getByCustomerSN(mainSN);
        for (var project : projectList) {
            var projectTagList = tagsDao.queryByMainSN(project.getSn(), Tl.getDBMapCode(UserInfoEntity.class));
            for (var projectTag : projectTagList) {
                projectTag.setTagSN(userSN);
                tagsDao.update(projectTag);
            }
        }
        return result;
    }

    @Autowired
    ICustomerInfoDao customerDao;

    @Autowired
    ISaleSysTagsService tagSvc;
    @Autowired
    ILinkerInfoDao linkerInfoDao;
    @Autowired
    ISaleContractDao contractdao;
    @Autowired
    IBuildProjectInfoDao projectInfoDao;
}
